package com.wwj.study.spring.formework.webmvc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WViewResolver {

    private String name;
    private File templatge;

    public WViewResolver(String name, File templatge) {
        this.name = name;
        this.templatge = templatge;
    }

    public String getName() {
        return name;
    }

    public File getTemplatge() {
        return templatge;
    }

    public String viewResolver(WModelAndView modelAndView) throws Exception {
        StringBuffer sb=new StringBuffer();

        //读文件
        RandomAccessFile ra = new RandomAccessFile(this.templatge,"r");
        String line= null;
        //一行一行的读文件
        while (null != (line=ra.readLine())){
            line = new String(line.getBytes("ISO-8859-1"), "utf-8");
            //正则查找
            Matcher m = matcher(line);
            //是否匹配成功
            while (m.find()) {
                //一行有好几个需要替换的
                for (int i = 1; i <= m.groupCount(); i++) {
                    //要把${}中间的这个字符串给取出来
                    String paramName = m.group(i);
                    Object paramValue = modelAndView.getModel().get(paramName);
                    if (null == paramValue) {
                        continue;
                    }
                    line = line.replaceAll("#\\{" + paramName + "\\}", paramValue.toString());
                    line = new String(line.getBytes("utf-8"), "ISO-8859-1");
                }
            }
            sb.append(line);
        }

        return sb.toString();
    }

    private Matcher matcher(String line) {
        //正则匹配 #{}
        Pattern pattern=Pattern.compile("#\\{(.+?)\\}",Pattern.CASE_INSENSITIVE);
        return pattern.matcher(line);

    }
}
